<template>
  <div>
    <div class='msg'>
      <div class='card'>
        <span class='card-o'></span>
        <span class='card-t'>修改信息</span>
      </div>
    </div>
    <div class='changeMsg'>
      <a-form :form='form' v-bind='formLayout'>
        <a-form-item label='主键' v-show='false'>
          <a-input
            v-decorator="['id']" disabled />
        </a-form-item>
        <a-form-item label='账号'>
          <a-input
            v-decorator="['username', {rules: [{ required: true, message: '请输入账号' }], validateTrigger: 'blur'}]"
            disabled />
        </a-form-item>
        <a-form-item label='用户名'>
          <a-input
            v-decorator="['nickName', {rules: [{ required: true, message: '请输入用户名' }], validateTrigger: 'blur'}]" />
        </a-form-item>
        <a-form-item label='联系电话'>
          <a-input
            v-decorator="['phone', {rules: [{ required: true, message: '请输入联系电话' }, { pattern: phonePattern,  message: '请输入合法电话'}], validateTrigger: 'blur'}]" />
        </a-form-item>
        <a-form-item label='头像'>
          <a-upload
            name='file'
            list-type='picture-card'
            class='avatar-uploader'
            :show-upload-list='false'
            v-decorator="['avatar',
            {
              valuePropName: 'file',
              getValueFromEvent: normFile,
            }]"
            :action='uploadPath'
            :headers='computedHeaders'
            :before-upload='beforeUpload'
            @change='handleChange'
          >
            <img class='avatar' v-if='imageUrl' :src='imageUrl' alt='avatar' />
            <div v-else>
              <a-icon :type="uploadLoading ? 'loading' : 'plus'" />
              <div class='ant-upload-text'>
                上传头像
              </div>
            </div>
          </a-upload>
        </a-form-item>
        <a-form-item :wrapper-col='{ span: 29, offset:4}'>
          <a-button type='primary' @click='handleSubmit'>
            提交
          </a-button>
        </a-form-item>
      </a-form>
    </div>
  </div>
</template>

<script>
import AvatarModal from '../../account/settings/AvatarModal'
import { updateUser } from '@/api/user'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { mapState } from 'vuex'
import api, { downloadAvatar } from '@/api/user'
import { findRoleByPage } from '@/api/role'
import { strPattern1 as userNamePattern, phonePattern } from '@/reges'
import pick from 'lodash.pick'
// 表单字段
const fields = ['id', 'username', 'phone', 'age', 'nickName', 'gender', 'avatar']
let baseUrl = window.PROJECT_CONFIG.VUE_APP_API_BASE_URL
export default {
  props: {
    loading: {
      type: Boolean,
      default: () => false
    },
    model: {
      type: Object,
      default: () => null
    }
  },
  computed: {
    ...mapState({
      token: state => state.user.token
    }),
    computedHeaders() {
      return {
        [ACCESS_TOKEN]: `Bearer ${this.token}`
      }
    }
  },
  data() {
    this.formLayout = {
      labelCol: {
        xs: { span: 20 },
        sm: { span: 4 }
      },
      wrapperCol: {
        xs: { span: 20 },
        sm: { span: 4 }
      }
    }
    return {
      baseurl: baseUrl,
      uploadPath: baseUrl + api.uploadAvatar,
      userNamePattern,
      phonePattern,
      roleList: [],
      roleIds: [],
      imageUrl: '',
      userInfos: {},
      id: '',
      uploadLoading: false,
      form: this.$form.createForm(this)
    }
  },
  created() {
    // 防止表单未注册
    fields.forEach(v => this.form.getFieldDecorator(v))
    this.$store.dispatch('GetInfo').then(res => {
      this.userInfos = res
      if (res) {
        this.form.setFieldsValue(pick(res, fields))
        if (res.avatar) {
          this.imageUrl = baseUrl + downloadAvatar({ fileName: res.avatar })
        }
      }
    })
  },
  methods: {
    handleSubmit() {
      this.userInfos = Object.assign(this.userInfos, this.form.getFieldsValue())
      this.form.validateFields(err => {
        if (!err) {
          delete this.userInfos.authorities
          delete this.userInfos.permissionList
          updateUser(this.userInfos).then(res => {
            this.$message.success('更新成功')
            this.$store.dispatch('GetInfo')
          })
        }
      })
    },
    async getRoleList() {
      const reulst = await findRoleByPage({ pageNo: 1, pageSize: 999, enabled: true })
      this.roleList = reulst.list
    },
    normFile(e) {
      if (Array.isArray(e)) {
        return e
      }
      return e && e.fileList && e.fileList[0].response && e.fileList[0].response.result
    },
    handleChange(info) {
      if (info.file.status === 'uploading') {
        this.uploadLoading = true
        return
      }
      if (info.file.status === 'done') {
        this.imageUrl = baseUrl + downloadAvatar({ fileName: info.file.response.result })
        this.uploadLoading = false
      }
    },
    beforeUpload(file) {
      const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
      if (!isJpgOrPng) {
        this.$message.error('仅支持JPEG格式以及PNG格式文件!')
      }
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!isLt2M) {
        this.$message.error('图片大小不得超过 10MB!')
      }
      return isJpgOrPng && isLt2M
    }
  }
}
</script>

<style lang='less'>
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}

.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}

.avatar {
  width: 130px;
  height: 130px;
}
</style>
